package com.sinosoft.cnmuseum.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sinosoft.cnmuseum.dao.MbGyFileDao;
import com.sinosoft.cnmuseum.entity.MbGyFile;
import com.sinosoft.cnmuseum.utils.MultipartFile;
import com.sinosoft.cnmuseum.utils.Status;
import com.sinosoft.commontools.annotated.CustomDataAnnotation;
import com.sinosoft.commontools.annotated.TransAnnotation;
import com.sinosoft.commontools.annotated.rquestMethod;
import com.sinosoft.commontools.annotated.rquestMethod.ReqMode;
import com.sinosoft.commontools.record.Record;

public class MbGyFileServlet {

	private static Logger logger = Logger.getLogger(MbGyFileServlet.class);
	
	/**
	 * 上传文件获取文件id
	 * @param request
	 * @param response
	 * @param data
	 * @return
	 */
	@rquestMethod(MethodNote = ReqMode.All)
	@TransAnnotation(isTrans=true)
	@CustomDataAnnotation(isCustomRead=true)
	public Record insert(HttpServletRequest request, HttpServletResponse response, Record data) {		
		Record result = new Record();
		try{			
			MultipartFile multipartFile =new MultipartFile();
			String fileid = multipartFile.getFileid(request);					
			result.add("id", fileid);
			result.add(Status.SATUS,Status.OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			// 事务回滚，事务模式下，此标识将使此次事务回滚
			result.add(Status.SATUS, Status.FAILED);
		}
	    return result;
	}

	/**
	 * 删除文件记录数据和本地文件
	 * @param request
	 * @param response
	 * @param data
	 * @return
	 */
	@rquestMethod(MethodNote = ReqMode.All)
	@TransAnnotation(isTrans=true)
	public Record delete(HttpServletRequest request, HttpServletResponse response, Record data) {
		// TODO Auto-generated method stub			
		Record result = new Record();
		try{			
			MultipartFile multipartFile =new MultipartFile();
			String fileid = data.getStrValue("id");			
			multipartFile.deleteFileData(fileid);
			result.add(Status.SATUS,Status.OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			// 事务回滚，事务模式下，此标识将使此次事务回滚
			result.add(Status.SATUS, Status.FAILED);
		}
	    return result;
	}
	
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param data
	 */
	@rquestMethod(MethodNote = ReqMode.All)
	public Record downFile(HttpServletRequest request, HttpServletResponse response, Record data){
		Record result = new Record();
		try {
			MbGyFileDao dao = new MbGyFileDao();
			String fileid = data.getStrValue("fileid");		
			String sql = "select * from "+MbGyFile.MB_GY_FILE_TABLE_NAME+" where 1=1 and "+MbGyFile.ID+"='"+fileid+"' ";
			List<Record> list = dao.getBySql(sql);	
			Record file = list.get(0);
			String filename = file.getStrValue("filename");
			String savePath = file.getStrValue("savePath");
			File newfile = new File(savePath);
			response.setCharacterEncoding("UTF-8");
			response.setContentLength((int) newfile.length()); 
			// 设置中文编码 防止乱码
			filename = new String(filename.getBytes(), "ISO-8859-1"); 
			// 设置在下载框默认显示的文件名  
            response.setHeader("Content-Disposition", "attachment;filename="+ filename);
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流  
            //读取文件  
            InputStream in = new FileInputStream(savePath);  
            OutputStream out = response.getOutputStream();  
            //写文件  
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
            	out.write(buff, 0, bytesRead);
            }
            in.close();  
            out.close(); 
		} catch (Exception e) {
			result.add(Status.MSG,"文件不存在!");
			try {
				response.setHeader("Content-type", "text/html;charset=UTF-8"); 
				response.setContentType("text/plain");
				response.setCharacterEncoding("UTF-8");
				String jsstr = "文件不存在";
				response.getOutputStream().write(jsstr.getBytes("UTF-8"));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return result;
	}
	
	
}
